package com.vhall.component.service.room.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vhall.component.dao.room.RecordOfRoomMapper;
import com.vhall.component.entity.record.RecordEntity;
import com.vhall.component.plugin.common.constant.HttpConstant;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.service.room.CallRecordService;
import com.vhall.component.service.room.concant.RoomConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author rui.zhou
 * @date 2021/5/11 18:45
 */
@Slf4j
@Service
public class CallRecordServiceImpl implements CallRecordService {


    @Autowired
    private PaasService paasService;

    /**
     * 现在的逻辑是paas只调用这一次的回调，然后在这个回调中去生成回放，这样会导致record服务和room服务发生循环依赖。
     * 所以在这里直接操作record表
     */
    @Autowired
    private RecordOfRoomMapper recordOfRoomMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String callBack(Map<String, Object> call) {
        String resp = RoomConstant.SUCCESS;
        String event = (String) call.get("event");

        if (com.vhall.component.plugin.common.constant.RoomConstant.EVENT_RECORD_COMPLETE.equals(event)) {
            log.info("开始CreateRecordComplete");
            resp = recordComplete(call);
        }
        if (com.vhall.component.plugin.common.constant.RoomConstant.EVENT_ALL_RECORD_COMPLETE.equals(event)) {
            log.info("开始AllTranscodeComplete");
            resp = allTransCodeComplete(call);
        }
        if (com.vhall.component.plugin.common.constant.RoomConstant.EVENT_MEDIA_PACKAGE_COMPLETE.equals(event)) {
            log.info("开始MediaPackageComplete");
            resp = eventMediaPackageComplete(call);
        }
        if (com.vhall.component.plugin.common.constant.RoomConstant.EVENT_VODTOLIVE_START.equals(event)) {
            log.info("开始VODToLiveStart");
            resp = eventVODToLiveStart(call);
        }
        if (com.vhall.component.plugin.common.constant.RoomConstant.EVENT_VODTOLIVE_END.equals(event)) {
            log.info("开始VODToLiveEnd");
            resp = eventVODToLiveEnd(call);
        }
        if (com.vhall.component.plugin.common.constant.RoomConstant.EVENT_VODTOLIVE_STOP.equals(event)) {
            log.info("开始VODToLiveStop");
            resp = eventVODToLiveStop(call);
        }
        return resp;
    }

    private String eventMediaPackageComplete(Map<String, Object> call) {
        String vodId = (String) call.get(RoomConstant.VOD_ID);
        String quality = (String) call.get("quality");
        String downloadUrl = (String) call.get("download_url");
        String key = StringUtils.isNotBlank(quality)
                ? RedisKey.RECORD_DOWN_QA_URL + vodId + ":" + quality
                : RedisKey.RECORD_DOWN_URL + vodId;
        if (StringUtils.isNotBlank(downloadUrl)) {
            redisTemplate.opsForValue().set(key, downloadUrl, 6, TimeUnit.DAYS);
        }
        return RoomConstant.SUCCESS;
    }

    /**
     * 全部转码完成回调
     *
     * @param call
     * @return
     */
    private String allTransCodeComplete(Map<String, Object> call) {
        String vodId = (String) call.get(RoomConstant.VOD_ID);
        RecordEntity recordEntity = recordOfRoomMapper.findByVodId(vodId);
        if (recordEntity != null) {
            recordEntity.setTranscodeStatus(Integer.valueOf(String.valueOf(call.get("status"))));
            recordEntity.setUpdatedAt(LocalDateTime.now());
            recordOfRoomMapper.updateById(recordEntity);
            JSONObject vodInfo = paasService.getRecordInfo(vodId);
            if (vodInfo.getInteger(HttpConstant.CODE) != HttpConstant.SUCCESS_CODE) {
                log.error("获取视频详细信息错误");
                return "fail";
            } else {
                JSONObject data = vodInfo.getJSONObject(HttpConstant.DATA);
                JSONObject vod = data.getJSONObject("vod_info");

                recordEntity.setDuration(vod.getInteger("duration"));
                recordEntity.setUpdatedAt(LocalDateTime.now());
                recordOfRoomMapper.updateById(recordEntity);
            }
        }
        return RoomConstant.SUCCESS;
    }

    /**
     * 生成回放成功
     *
     * @param call
     * @return
     */
    private String recordComplete(Map<String, Object> call) {
        Integer status = Integer.valueOf(String.valueOf(call.get("status")));
        if ("1".equals(status.toString())) {
            String vodId = (String) call.get(RoomConstant.VOD_ID);
            JSONObject vodInfo = paasService.getRecordInfo(vodId);
            if (vodInfo.getInteger(HttpConstant.CODE) != HttpConstant.SUCCESS_CODE) {
                log.error("获取视频详细信息错误");
                return "fail";
            } else {
                RecordEntity recordEntity = recordOfRoomMapper.findByVodId(vodId);
                if (recordEntity != null) {
                    JSONObject data = vodInfo.getJSONObject(HttpConstant.DATA);
                    JSONObject vod = data.getJSONObject("vod_info");
                    recordEntity.setStorage(vod.getInteger("storage"));
                    recordEntity.setDuration(vod.getInteger("duration"));
                    recordEntity.setUpdatedAt(LocalDateTime.now());
                    recordOfRoomMapper.updateById(recordEntity);
                }
            }
        }
        return RoomConstant.SUCCESS;
    }


    private String eventVODToLiveStart(Map<String, Object> call) {
        log.info(JSON.toJSONString(call));
        return RoomConstant.SUCCESS;
    }

    private String eventVODToLiveEnd(Map<String, Object> call) {
        log.info(JSON.toJSONString(call));
        return RoomConstant.SUCCESS;
    }

    private String eventVODToLiveStop(Map<String, Object> call) {
        log.info(JSON.toJSONString(call));
        return RoomConstant.SUCCESS;
    }
}
